package com.example.livedatademo;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.livedatademo.livedata.TimerLiveDataViewModel;

public class MainActivity extends AppCompatActivity {
    private TextView tvTime, tvRestart;
    private MutableLiveData<Integer> liveData;
    private TimerLiveDataViewModel timerLiveDataViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initLiveData();
    }

    private void initView() {
        tvTime = findViewById(R.id.tv_time);
        tvRestart = findViewById(R.id.tv_restart);
    }

    private void initLiveData() {
        //得到ViewModel中LiveData
        timerLiveDataViewModel = new ViewModelProvider(this).get(TimerLiveDataViewModel.class);
        liveData = (MutableLiveData<Integer>) timerLiveDataViewModel.getCurrentSecond();
        //通过LiveData.Observe()观察ViewModel中数据的变化
        liveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer second) {
                tvTime.setText("Time : " + second);
            }
        });
        //重置计时器
        tvRestart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //完成ViewModel中数据的更新
                liveData.setValue(0);//setValue()只能在主线程中调用

            }
        });
        //计时开始
        timerLiveDataViewModel.startTiming();
    }
}